package io.renren.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Auther: miaoguoxin
 * @Date: 2019/11/12 21:40
 * @Description: 微信支付工具
 */
@Slf4j
public class WxUtils {
    /**
     * 第一次签名
     *
     * @param params 数据为服务器生成，下单时必须的字段排序签名
     * @param key
     * @return
     */
    public static String createSign(Object params, String key) {
        String json = JSON.toJSONString(params, SerializerFeature.SortField);
        JSONObject jsonObj = JSON.parseObject(json, Feature.OrderedField);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);
        return  Md5Util.getInstance().getmd5Code(sb.toString());
    }

    /**
    * @Description: 签名校验
    * @Param:
    * @return:
    * @Author: miaoguoxin
    * @Date: 2019/11/16
    */
    public static boolean validateSign(Map<String,String> paramMap,String key){
        String signFromAPIResponse = paramMap.get("sign");
        if (StringUtil.isEmpty(signFromAPIResponse)) {
            log.warn("API返回的数据签名数据不存在，有可能被第三方篡改!!!");
            return false;
        }
        SortedMap<String,String> packageParams = new TreeMap<>();

        for (String parameter : paramMap.keySet()) {
            String parameterValue = paramMap.get(parameter);
            String v = "";
            if (null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }

        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, String>> entries = packageParams.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String k = entry.getKey();
            String v = entry.getValue();
            if (!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);

        //将API返回的数据根据用签名算法进行计算新的签名，用来跟API返回的签名进行比较
        //算出签名
        String tobesign = sb.toString();
        String resultSign = Md5Util.getInstance().getmd5Code(tobesign);
        String tenpaySign = packageParams.get("sign").toUpperCase();
        return tenpaySign.equals(resultSign);

    }


}
